package com.yami.shop.distribution.common.listener;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yami.shop.bean.enums.ShopStatus;
import com.yami.shop.bean.event.ShopChangeStatusEvent;
import com.yami.shop.distribution.common.constants.DistributionProdStateEnum;
import com.yami.shop.distribution.common.model.DistributionProd;
import com.yami.shop.distribution.common.service.DistributionProdService;
import lombok.AllArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 店铺改变状态监听
 *
 * @Author lth
 * @Date 2021/11/22 17:18
 */
@Component("distributionShopChangeStatusListener")
@AllArgsConstructor
public class ShopChangeStatusListener {

    private final DistributionProdService distributionProdService;

    @EventListener(ShopChangeStatusEvent.class)
    public void distributionShopChangeStatusListener(ShopChangeStatusEvent event) {
        Long shopId = event.getShopId();
        ShopStatus shopStatus = event.getShopStatus();
        if (Objects.isNull(shopId) || Objects.isNull(shopStatus)) {
            return;
        }
        if (Objects.equals(shopStatus, ShopStatus.OFFLINE)) {
            // 店铺下线时，把上架状态的分销商品置为下架
            distributionProdService.update(Wrappers.lambdaUpdate(DistributionProd.class)
                    .set(DistributionProd::getState, DistributionProdStateEnum.PUT_OFF.getValue())
                    .eq(DistributionProd::getShopId, shopId)
                    .eq(DistributionProd::getState, DistributionProdStateEnum.PUT_ON.getValue())
            );
        }
    }
}
